//package com.example.app.service;
//
//import com.example.app.config.BaiduApiConfig;
//import com.example.app.dto.BaiduTokenResponse;
//import com.example.app.dto.FoodRecognitionResult;
//import lombok.RequiredArgsConstructor;
//import lombok.extern.slf4j.Slf4j;
//import okhttp3.*;
//import org.json.JSONObject;
//import org.springframework.stereotype.Service;
//import org.springframework.web.multipart.MultipartFile;
//
//import java.io.IOException;
//import java.util.Base64;
//import java.util.concurrent.TimeUnit;
//
//@Slf4j
//@Service
//@RequiredArgsConstructor
//public class BaiduFoodRecognitionService {
//
//    private final BaiduApiConfig baiduApiConfig;
//
//    private OkHttpClient httpClient;
//
//    private String cachedAccessToken;
//    private long tokenExpireTime;
//
//    // 初始化HTTP客户端
//    private OkHttpClient getHttpClient() {
//        if (httpClient == null) {
//            httpClient = new OkHttpClient.Builder()
//                    .connectTimeout(10, TimeUnit.SECONDS)
//                    .readTimeout(baiduApiConfig.getTimeout(), TimeUnit.SECONDS)
//                    .build();
//        }
//        return httpClient;
//    }
//
//    // 获取Access Token
//    private String getAccessToken() throws IOException {
//        // 如果token未过期且存在，直接返回缓存的token
//        if (cachedAccessToken != null && System.currentTimeMillis() < tokenExpireTime) {
//            return cachedAccessToken;
//        }
//
//        // 构建请求体
//        FormBody formBody = new FormBody.Builder()
//                .add("grant_type", "client_credentials")
//                .add("client_id", baiduApiConfig.getKey())
//                .add("client_secret", baiduApiConfig.getSecret())
//                .build();
//
//        // 创建请求
//        Request request = new Request.Builder()
//                .url(baiduApiConfig.getTokenUrl())
//                .post(formBody)
//                .build();
//
//        // 发送请求
//        try (Response response = getHttpClient().newCall(request).execute()) {
//            if (!response.isSuccessful()) {
//                throw new IOException("获取Access Token失败: " + response.code() + " - " + response.message());
//            }
//
//            String responseBody = response.body().string();
//            JSONObject json = new JSONObject(responseBody);
//            BaiduTokenResponse tokenResponse = new BaiduTokenResponse();
//            tokenResponse.setAccessToken(json.getString("access_token"));
//            tokenResponse.setExpiresIn(json.getLong("expires_in"));
//
//            // 缓存Token信息
//            cachedAccessToken = tokenResponse.getAccessToken();
//            tokenExpireTime = System.currentTimeMillis() + (tokenResponse.getExpiresIn() - 300) * 1000; // 提前5分钟刷新
//
//            return cachedAccessToken;
//        }
//    }
//
//    // 识别食物
//    public FoodRecognitionResult recognizeFood(MultipartFile file) throws IOException {
//        String accessToken = getAccessToken();
//        String imageBase64 = encodeImageToBase64(file);
//
//        // 构建请求体
//        FormBody formBody = new FormBody.Builder()
//                .add("image", imageBase64)
//                .build();
//
//        // 创建请求
//        String dishUrl = baiduApiConfig.getDishUrl() + "?access_token=" + accessToken;
//        Request request = new Request.Builder()
//                .url(dishUrl)
//                .post(formBody)
//                .addHeader("Content-Type", "application/x-www-form-urlencoded")
//                .build();
//
//        // 发送请求
//        try (Response response = getHttpClient().newCall(request).execute()) {
//            if (!response.isSuccessful()) {
//                throw new IOException("菜品识别失败: " + response.code() + " - " + response.message());
//            }
//
//            String responseBody = response.body().string();
//            JSONObject json = new JSONObject(responseBody);
//            FoodRecognitionResult result = new FoodRecognitionResult();
//            result.setLogId(json.getLong("log_id"));
//            result.setResultNum(json.getInt("result_num"));
//
//            // 解析识别结果（实际开发中需要更详细的映射）
//            // 这里简化处理，实际应用中应根据百度API返回结构创建完整DTO
//
//            return result;
//        }
//    }
//
//    // 图片转Base64
//    private String encodeImageToBase64(MultipartFile file) throws IOException {
//        byte[] fileBytes = file.getBytes();
//        return Base64.getEncoder().encodeToString(fileBytes);
//    }
//}

package com.example.app.service;

import com.example.app.config.BaiduApiConfig;
import com.example.app.dto.BaiduTokenResponse;
import com.example.app.dto.FoodRecognitionResult;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
@RequiredArgsConstructor
public class BaiduFoodRecognitionService {

    private final BaiduApiConfig baiduApiConfig;

    private OkHttpClient httpClient;

    private String cachedAccessToken;
    private long tokenExpireTime;

    // 初始化HTTP客户端
    private OkHttpClient getHttpClient() {
        if (httpClient == null) {
            httpClient = new OkHttpClient.Builder()
                    .connectTimeout(10, TimeUnit.SECONDS)
                    .readTimeout(baiduApiConfig.getTimeout(), TimeUnit.SECONDS)
                    .build();
        }
        return httpClient;
    }

    // 获取Access Token
    private String getAccessToken() throws IOException {
        // 如果token未过期且存在，直接返回缓存的token
        if (cachedAccessToken != null && System.currentTimeMillis() < tokenExpireTime) {
            return cachedAccessToken;
        }

        // 构建请求体
        FormBody formBody = new FormBody.Builder()
                .add("grant_type", "client_credentials")
                .add("client_id", baiduApiConfig.getKey())
                .add("client_secret", baiduApiConfig.getSecret())
                .build();

        // 创建请求
        Request request = new Request.Builder()
                .url(baiduApiConfig.getTokenUrl())
                .post(formBody)
                .build();

        // 发送请求
        try (Response response = getHttpClient().newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("获取Access Token失败: " + response.code() + " - " + response.message());
            }

            String responseBody = response.body().string();
            JSONObject json = new JSONObject(responseBody);

            // 检查错误响应
            if (json.has("error")) {
                String error = json.getString("error");
                String errorDescription = json.optString("error_description", "未知错误");
                throw new IOException("获取AccessToken失败: " + error + " - " + errorDescription);
            }

            BaiduTokenResponse tokenResponse = new BaiduTokenResponse();
            tokenResponse.setAccessToken(json.getString("access_token"));
            tokenResponse.setExpiresIn(json.getLong("expires_in"));
            tokenResponse.setRefreshToken(json.optString("refresh_token", ""));
            tokenResponse.setScope(json.optString("scope", ""));
            tokenResponse.setSessionKey(json.optString("session_key", ""));
            tokenResponse.setSessionSecret(json.optString("session_secret", ""));

            // 缓存Token信息
            cachedAccessToken = tokenResponse.getAccessToken();
            tokenExpireTime = System.currentTimeMillis() + (tokenResponse.getExpiresIn() - 300) * 1000; // 提前5分钟刷新

            return cachedAccessToken;
        }
    }

    // 识别食物 - 完整实现
    public FoodRecognitionResult recognizeFood(MultipartFile file) throws IOException {
        // 1. 获取Access Token
        String accessToken = getAccessToken();

        // 2. 转换图片为Base64
        byte[] fileBytes = file.getBytes();
        String imageBase64 = Base64.getEncoder().encodeToString(fileBytes);

        // 3. 构建请求体
        FormBody formBody = new FormBody.Builder()
                .add("image", imageBase64)
                // 可选：添加其他参数，如是否检测卡路里等
                .add("top_num", "5")
                .build();

        // 4. 创建请求
        String dishUrl = baiduApiConfig.getDishUrl() + "?access_token=" + accessToken;
        Request request = new Request.Builder()
                .url(dishUrl)
                .post(formBody)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();

        // 5. 发送请求并解析响应
        try (Response response = getHttpClient().newCall(request).execute()) {
            // 5.1 检查HTTP响应状态
            if (!response.isSuccessful()) {
                // 尝试从响应体获取更多错误信息
                String errorBody = response.body() != null ? response.body().string() : "";
                try {
                    // 尝试解析为JSON错误
                    JSONObject errorJson = new JSONObject(errorBody);
                    if (errorJson.has("error_code") && errorJson.has("error_msg")) {
                        throw new IOException("百度API错误: " +
                                errorJson.getInt("error_code") + " - " +
                                errorJson.getString("error_msg"));
                    }
                } catch (JSONException e) {
                    // 不是JSON格式的错误响应
                }
                throw new IOException("菜品识别失败: " + response.code() + " - " + response.message());
            }

            // 5.2 解析响应体
            String responseBody = response.body().string();
            JSONObject json = new JSONObject(responseBody);

            // 5.3 检查API错误码
            if (json.has("error_code")) {
                int errorCode = json.getInt("error_code");
                String errorMsg = json.optString("error_msg", "未知错误");
                throw new IOException("百度API错误: " + errorCode + " - " + errorMsg);
            }

            // 5.4 创建结果对象
            FoodRecognitionResult result = new FoodRecognitionResult();

            // 5.5 设置基础字段
            if (json.has("log_id")) {
                result.setLogId(json.getLong("log_id"));
            }

            if (json.has("result_num")) {
                result.setResultNum(json.getInt("result_num"));
            }

            // 5.6 解析结果列表
            if (json.has("result") && !json.isNull("result")) {
                JSONArray results = json.getJSONArray("result");
                List<FoodRecognitionResult.ResultItem> resultItems = new ArrayList<>();

                for (int i = 0; i < results.length(); i++) {
                    JSONObject item = results.getJSONObject(i);
                    FoodRecognitionResult.ResultItem resultItem = parseResultItem(item);
                    resultItems.add(resultItem);
                }
                result.setResult(resultItems);
            } else {
                result.setResult(Collections.emptyList());
            }

            // 5.7 解析定位信息（如果有多道菜在同一张图片中）
            if (json.has("location_result")) {
                JSONObject locationResult = json.getJSONObject("location_result");
                FoodRecognitionResult.Location location = new FoodRecognitionResult.Location();

                if (locationResult.has("width")) {
                    location.setWidth(locationResult.getInt("width"));
                }
                if (locationResult.has("height")) {
                    location.setHeight(locationResult.getInt("height"));
                }
                if (locationResult.has("top")) {
                    location.setTop(locationResult.getInt("top"));
                }
                if (locationResult.has("left")) {
                    location.setLeft(locationResult.getInt("left"));
                }

                result.setLocation(location);
            }

            return result;
        } catch (JSONException e) {
            log.error("解析JSON响应失败", e);
            throw new IOException("无效的API响应格式");
        }
    }

    // 解析单个结果项
    private FoodRecognitionResult.ResultItem parseResultItem(JSONObject item) {
        FoodRecognitionResult.ResultItem resultItem = new FoodRecognitionResult.ResultItem();

        // 设置基本字段
        resultItem.setName(item.optString("name", "未知"));
        resultItem.setProbability(item.optDouble("probability", 0.0));
        resultItem.setCalorie(item.optString("calorie", "未知"));

        // 解析卡路里数值
        parseCalorieInfo(item, resultItem);

        // 解析百度百科信息
        if (item.has("baike_info")) {
            JSONObject baikeInfo = item.getJSONObject("baike_info");
            FoodRecognitionResult.BaikeInfo baike = new FoodRecognitionResult.BaikeInfo();

            baike.setBaikeUrl(baikeInfo.optString("baike_url", ""));
            baike.setImageUrl(baikeInfo.optString("image_url", ""));
            baike.setDescription(baikeInfo.optString("description", ""));

            resultItem.setBaikeInfo(baike);
        }

        // 设置位置信息（如果在图像中有位置）
        if (item.has("location")) {
            JSONObject location = item.getJSONObject("location");
            FoodRecognitionResult.Location loc = new FoodRecognitionResult.Location();

            if (location.has("top")) {
                loc.setTop(location.getInt("top"));
            }
            if (location.has("left")) {
                loc.setLeft(location.getInt("left"));
            }
            if (location.has("width")) {
                loc.setWidth(location.getInt("width"));
            }
            if (location.has("height")) {
                loc.setHeight(location.getInt("height"));
            }

            resultItem.setLocation(loc);
        }

        return resultItem;
    }

    // 解析卡路里信息
    private void parseCalorieInfo(JSONObject item, FoodRecognitionResult.ResultItem resultItem) {
        String calorie = resultItem.getCalorie();
        System.out.println(calorie);
        if (!calorie.isEmpty()) {
            try {
                System.out.println(1222);
                double calorieNum = Double.parseDouble(calorie);
                resultItem.setCalorieNum(calorieNum);
                resultItem.setHasCalorie(true);
                resultItem.setCalorie(calorieNum + "大卡/100克");
            } catch (NumberFormatException e) {
                resultItem.setHasCalorie(false);
            }
        } else {
            resultItem.setHasCalorie(false);
        }
    }

    // 图片转Base64
    private String encodeImageToBase64(MultipartFile file) throws IOException {
        byte[] fileBytes = file.getBytes();
        return Base64.getEncoder().encodeToString(fileBytes);
    }
}